import { ref } from 'vue';
import { TableRowSelection } from '@arco-design/web-vue';

interface UseTableSelectionParams {
  rowSelection?: TableRowSelection;
  onSelectionChange?: (a?: any[]) => void;
  afterReq?: (a: any) => any;
  rowKey?: string;
}

export default function useTableSelect(params?: UseTableSelectionParams) {
  const initRowSelection = (): TableRowSelection => {
    return {
      type: 'checkbox',
      showCheckedAll: true,
      ...(params?.rowSelection || {}),
    };
  };

  const rowSelection = ref<TableRowSelection | undefined>(initRowSelection());

  const selectIds = ref<any[]>([]);
  const rowKey = ref(params?.rowKey || 'id');

  const onSelectionChange = (rowKeys: any[]) => {
    selectIds.value = rowKeys;
    if (params?.onSelectionChange) {
      params?.onSelectionChange(rowKeys);
    }
  };

  // 提供给useTable使用，每次请求清空选择项
  const afterReq = (res: any) => {
    selectIds.value = [];
    if (params?.afterReq) {
      return params.afterReq(res);
    }
    return res;
  };

  // 开启关闭选择框
  const toggleSelect = (toggle: 'close' | 'open') => {
    if (toggle === 'close') {
      rowSelection.value = undefined;
    }

    if (toggle === 'open') {
      selectIds.value = [];
      rowSelection.value = initRowSelection();
    }
  };

  return {
    rowKey,
    selectIds,
    rowSelection,
    onSelectionChange,
    afterReq,
    toggleSelect,
  };
}
